package com.cn.lp.jpa.cq.domain;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;
import java.util.Objects;

public class CQField {

    /**
     * 字段名
     */
    private String name;
    /**
     * 指定类型
     */
    Class<?> asClass;

    private CQField() {
    }

    public static CQField ofName(String name) {
        var field = new CQField();
        field.name = name;
        return field;
    }

    public String getName() {
        return name;
    }

    public CQField as(Class<?> clazz) {
        asClass = clazz;
        return this;
    }

    public CQField asString() {
        return as(String.class);
    }

    @SuppressWarnings("unchecked")
    public <X> Expression<X> toExpression(Root<?> root) {
        return Objects.isNull(asClass) ? root.get(name) : root.get(name).as((Class<X>) asClass);
    }

}
